import * as toolUtil from "./ckextraToolUtil";
import editorUtil from "./ckextraEditorUtil";
const insertElementWithOutSaveTodo = (element,isAfter) => {
  editorUtil.lock();
  CKEditorParams.editorObject.insertElement( element );
  setTimeout(() => {
    editorUtil.unlock();
  }, 0 )
}

// /** 设置单个修订信息 */
// const setSingleReviseItem=(element,type)=>{
// 	//CKEditorParams.editorObject.undoManager.lock(true);
// 	if(type == 'del'){
// 		type = "删除的内容";
// 	}else if(type == 'ins'){
// 		type = "插入的内容";
// 	}
// 	const boxDom = document.getElementById("revise");
// 	let div;
// 	//如果修订信息已存在，则不进行添加
// 	if(element.getAttribute("id") != null && element.getAttribute("id") != '' && jQuery('div[revsiseid="' + element.getAttribute("id") + '"]').length > 0){
// 		div = jQuery('div[revsiseid="' + element.getAttribute("id") + '"]')[0];
// 	}else{
// 		div = document.createElement("div");
// 		CKEditorParams.reviseCount += 1;
// 	}
// 	div.setAttribute("class","revise-item");
// 	div.setAttribute("id","reviseItem"+CKEditorParams.reviseCount);
// 	div.setAttribute("revsiseid",element.getAttribute("id"));
// 	const dateStr = getTagTime(element.getAttribute("xiudingshijian"))
// 	const xiudingren = element.getAttribute("xiudingren");
// 	const html = '<div class="revise-top"><span class="revise-item-name">'+xiudingren+'</span><span class="revise-item-type">'+type+'</span></div><div class="postilTime">'+dateStr+'<div class="revise-bottom">'+element.innerText+'</div>';
// 	div.innerHTML = html;
// 	boxDom.appendChild(div);
// 	document.getElementsByClassName("title-number")[0].innerText = recountReviseNumber();
// 	resetSingleReviseItem();
// 	//CKEditorParams.editorObject.undoManager.unlock(true);
// }


// const resetSingleReviseItem=()=>{
// 	const boxDom = document.getElementById("revise");
// 	jQuery(boxDom).find('.revise-item').each(function(index,ele){
// 		if(ele.getAttribute('revsiseid') === null || jQuery('#' + ele.getAttribute('revsiseid'),jQuery(".cke_wysiwyg_frame")[0].contentWindow.document).length <= 0){
// 			ele.remove();
// 		}
// 	});
// }

// //获取修订条数
// const recountReviseNumber=()=>{
//   const boxDom = document.getElementById("revise");
// 	return boxDom.childNodes.length - 1 + "处修订";
// }

const TagUtil = {
  insertElementWithOutSaveTodo,

  // insertTempUtag(words,revision, insert = false){ // fix: 修订模式，接受拒绝修订后，获得焦点光标是黑色的。insert: 必须插入的情况
  //   let isAddtag = true;
  //   const activeObj = editorUtil.getEditor().getSelection().getNative().focusNode;
  //   let tagName = activeObj.tagName, parentTagName = activeObj.parentNode.tagName;

  //   // fix: 用户更改，开始的痕迹记录仍为上一个用户的 (判断如果当前用户和焦点位置的用户是不是一个用户)
  //   let changeAuthor = false;
  //   const preAuthor = activeObj.parentNode.getAttribute('xiudingren');
  //   if (revision && preAuthor !== CKEditorParams.author) {
  //     changeAuthor = true;
  //   }
  //   // if(revision && tagName != 'U' && parentTagName != 'U') {
  //   const insertU = revision && tagName != 'U' && parentTagName != 'U';
  //   if(insert || changeAuthor || insertU) {
  //     const range = CKEditorParams.editorObject.createRange();
  //     let uElement = CKEditorParams.editorObject.document.createElement( 'u', {
  //       attributes: {
  //         class: 'odoc_insertTag',
  //         xiudingren: CKEditorParams.author,
  //         xiudingshijian: toolUtil.getDate(),
  //       },
  //     });
  //     uElement.setText(words?words:'');
  //     if(CKEditorParams.editorObject.getSelection().getRanges()[0]){
  //       const selectedRange = CKEditorParams.editorObject.getSelection().getRanges()[0];
  //       const {startOffset,endOffset,startContainer,endContainer} = selectedRange;
  //       //节点末尾为POST判断
  //       if(startContainer.equals(endContainer)
  //         && startOffset === endOffset
  //         && startContainer.getLength && startOffset === startContainer.getLength()
  //         && startContainer.$.nextElementSibling
  //         && startContainer.$.nextElementSibling.tagName === 'POSTIL'
  //         && startContainer.$.nextElementSibling.getAttribute('type') === 'end'
  //       ){
  //         const rangeTemp = CKEditorParams.editorObject.createRange();
  //         rangeTemp.moveToPosition( new CKEDITOR.dom.element( startContainer.$.nextElementSibling), CKEDITOR.POSITION_AFTER_END);
  //         rangeTemp.select();
  //       }
  //       //节点开始为POST判断
  //       if(startContainer.equals(endContainer)
  //         && startOffset === endOffset
  //         && startOffset === 0
  //         && startContainer.$.previousElementSibling
  //         && startContainer.$.previousElementSibling.tagName === 'POSTIL'
  //         && startContainer.$.previousElementSibling.getAttribute('type') === 'start'
  //       ){
  //         const rangeTemp = CKEditorParams.editorObject.createRange();
  //         rangeTemp.moveToPosition( new CKEDITOR.dom.element( startContainer.$.previousElementSibling), CKEDITOR.POSITION_BEFORE_START);
  //         rangeTemp.select();
  //       }
  //     }
  //     insertElementWithOutSaveTodo( uElement );

  //     range.moveToPosition( uElement, CKEDITOR.POSITION_BEFORE_END);
  //     range.select();
  //     return isAddtag;
  //   }
  //   if(parentTagName == "U" || parentTagName == "S"){
  //     isAddtag = false;
  //     return isAddtag
  //   }
    
  // },
  insertTempUtag(words,revision, insert = false){ // fix: 修订模式，接受拒绝修订后，获得焦点光标是黑色的。insert: 必须插入的情况
    let isAddtag = true;
    const activeObj = editorUtil.getEditor().getSelection().getNative().focusNode;
    const tagName = activeObj && activeObj.tagName;
    const parentTagName = activeObj && activeObj.parentNode && activeObj.parentNode.tagName;

    // fix: 用户更改，开始的痕迹记录仍为上一个用户的 (判断如果当前用户和焦点位置的用户是不是一个用户)
    let changeAuthor = false;
    const preAuthor = activeObj && activeObj.parentNode && activeObj.parentNode.getAttribute('xiudingren');
    if (revision && preAuthor !== CKEditorParams.author) {
      changeAuthor = true;
    }
    // if(revision && tagName != 'U' && parentTagName != 'U') {
    const insertU = revision && tagName != 'U' && (parentTagName != 'U' || words);
    if(insert || changeAuthor || insertU) {
      const range = CKEditorParams.editorObject.createRange();
      let uElement = CKEditorParams.editorObject.document.createElement( 'u', {
        attributes: {
          class: 'odoc_insertTag',
          xiudingren: CKEditorParams.author,
          xiudingshijian: toolUtil.getDate(),
        },
      });
      uElement.setText(words?words:'');
      //清除临时U标签
      clearTempUTag();
      if(CKEditorParams.editorObject.getSelection().getRanges()[0]){
        const selectedRange = CKEditorParams.editorObject.getSelection().getRanges()[0];
        const {startOffset,endOffset,startContainer,endContainer} = selectedRange;
        if(startOffset===endOffset
            && endContainer.equals(startContainer)){
          //节点末尾为POST判断
          if(((endContainer.getLength && endOffset === startContainer.getLength()) || (endContainer.$.tagName == 'U' || endContainer.$.tagName == 'S' ))
            && endContainer.$.nextElementSibling
            && endContainer.$.nextElementSibling.tagName === 'POSTIL'
            && endContainer.$.nextElementSibling.getAttribute('type') === 'end'
          ){
            const rangeTemp = CKEditorParams.editorObject.createRange();
            rangeTemp.moveToPosition( new CKEDITOR.dom.element( endContainer.$.nextElementSibling), CKEDITOR.POSITION_AFTER_END);
            rangeTemp.select();
          }else if(endContainer.getChild && endContainer.getChild(endOffset - 1)
            && endContainer.getChild(endOffset - 1).$.tagName === 'POSTIL'
            && endContainer.getChild(endOffset - 1).$.getAttribute('type') === 'end'
          ){
            const rangeTemp = CKEditorParams.editorObject.createRange();
            rangeTemp.moveToPosition( endContainer.getChild(endOffset - 1), CKEDITOR.POSITION_AFTER_END);
            rangeTemp.select();
          //节点开始为POST判断
          }else if((startOffset === 0 || endContainer.$.tagName == 'U' || endContainer.$.tagName == 'S' )
              && startContainer.$.previousElementSibling
              && startContainer.$.previousElementSibling.tagName === 'POSTIL'
              && startContainer.$.previousElementSibling.getAttribute('type') === 'start'
          ){
            const rangeTemp = CKEditorParams.editorObject.createRange();
            rangeTemp.moveToPosition( new CKEDITOR.dom.element( startContainer.$.previousElementSibling), CKEDITOR.POSITION_BEFORE_START);
            rangeTemp.select();
          }else if(startContainer.getChild && startContainer.getChild(endOffset - 1)
              && startContainer.getChild(startOffset - 1).$.tagName === 'POSTIL'
              && startContainer.getChild(startOffset - 1).$.getAttribute('type') === 'start'
          ){
            const rangeTemp = CKEditorParams.editorObject.createRange();
            rangeTemp.moveToPosition(startContainer.getChild(startOffset - 1), CKEDITOR.POSITION_BEFORE_START);
            rangeTemp.select();
          //POSTIL标签判断
          }else if(endContainer.$.tagName === 'POSTIL'
            && endContainer.$.getAttribute('type') === 'end'
          ){
            const rangeTemp = CKEditorParams.editorObject.createRange();
            rangeTemp.moveToPosition( endContainer, CKEDITOR.POSITION_AFTER_END);
            rangeTemp.select();
          }else if(startContainer.$.tagName === 'POSTIL'
            && startContainer.$.getAttribute('type') === 'start'
          ){
            const rangeTemp = CKEditorParams.editorObject.createRange();
            rangeTemp.moveToPosition( startContainer, CKEDITOR.POSITION_BEFORE_START);
            rangeTemp.select();
          }
        }
      }
      insertElementWithOutSaveTodo( uElement );

      range.moveToPosition( uElement, CKEDITOR.POSITION_BEFORE_END);
      range.select();
      return isAddtag;
    }
    if(parentTagName == "U" || parentTagName == "S"){
      isAddtag = false;
      return isAddtag
    }
    
  },

  clearTempUTag(needSiblingPostil){
    const UTags = iframeDocument.getElementsByTagName("body")[0].getElementsByTagName("u");
    // let maxid = 1;
    //获取最大的ID
    for(var i = 0;i < UTags.length; i++){
      const UTag = UTags[i];
      //删除内容为空的标签
      if(UTag.innerHTML =='' || UTag.innerHTML.replace(/\u200B/g,"") == ''){
        
        const UTagParent = UTag.parentNode;
        UTag.remove();
        UTagParent.normalize();
        i--;
      }
    }
  },
  //清除BR标签
  clearBrTag(){
    const BRTags = iframeDocument.getElementsByTagName("body")[0].getElementsByTagName("br");
    for(var i = 0;i < BRTags.length; i++){
      const BRTag = BRTags[i];
      if(BRTag.previousElementSibling != null || BRTag.nextElementSibling != null){
        BRTag.remove();
        BRTag.normalize();
        i--;
      }
    }
  },
  //清除BR标签
  clearTempTextTag(){
    const temptextTags = iframeDocument.getElementsByTagName("body")[0].getElementsByTagName("temptext");
    for(let i = 0; i <temptextTags.length; i++) {
      temptextTags[i].remove();
      i--;
    }
  },
  //遍历U标签，填充信息
  setUTagDesc(revising){
    //CKEditorParams.editorObject.undoManager.lock(true);
    //U标签加上ID
    const UTags = iframeDocument.getElementsByTagName("body")[0].getElementsByTagName("u");
    const author = JSON.parse(localStorage.getItem("theme-account")).username;
    let maxid = 1;
    //获取最大的ID
    for(let i = 0;i < UTags.length; i++){
      const UTag = UTags[i];
      //略过内容为空的标签
      if(UTag.innerHTML =='' || UTag.innerHTML.replace(/\u200B/g,"") == ''){
        continue;
      } 
      if(UTag.getAttribute("id") != '' && parseInt(UTag.getAttribute("id"),10) >= 0){
        const uid = parseInt(UTag.getAttribute("id"));
        maxid = maxid > uid ? maxid : uid;
      } 
    }
    //设置没有ID的标签
    for(let i = 0;i < UTags.length; i++){
      
      const UTag = UTags[i];
      // UTag.innerHTML = UTag.innerHTML.replace(/\u200B/g,'')
      if(!(parseInt(UTag.getAttribute("id"),10) > 0)){
        if(UTag.innerHTML =='' || UTag.innerHTML.replace(/\u200B/g,'') == ''){
          continue;
        }
        maxid++;
        UTag.setAttribute("id",maxid);
        if(revising){
          UTag.setAttribute("class",'odoc_insertTag');
        }else{
          UTag.setAttribute("class",'odoc_insertTag hiddenRevision_u');
        }
        UTag.setAttribute("xiudingren",author);
        UTag.setAttribute("xiudingshijian",toolUtil.getDate());
      }
    }
  },
  //如果P标签没有内容，增加br标签
  setBrInNullPtag(){
		let pTagList = iframeDocument.getElementsByTagName("body")[0].getElementsByTagName("p");
		for(let i = 0;i < pTagList.length; i++){
			let ptag = pTagList[i];
			if(ptag.innerHTML.trim() === ''){
				ptag.innerHTML = '<br/>';
			}
		}
  }

}
export default TagUtil;